package com.prince.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.prince.bean.CommonWebResponse;
import com.prince.bean.ResultParams;
import com.prince.bean.WebCode;
import com.prince.constant.Constants;
import com.prince.mapper.RoleMapper;
import com.prince.mapper.UserMapper;
import com.prince.mapper.x.RoleLimitsMapper;
import com.prince.mapper.x.UserLimitsMapper;
import com.prince.model.Limits;
import com.prince.model.Role;
import com.prince.model.RoleExample;
import com.prince.model.RoleExample.Criteria;
import com.prince.model.User;
import com.prince.page.Page;
import com.prince.util.ListUtils;
import com.prince.util.MapUtil;
import com.prince.util.StringUtil;
import com.prince.web.base.BaseService;
import com.prince.web.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 角色
 * @author WangPeiXi
 *
 */
@Service
public class RoleServiceImpl extends BaseService implements RoleService {

	@Resource
	private RoleMapper roleMapper;

	@Resource
	private RoleLimitsMapper roleLimitsMapper;
	
//	@Resource
//	private LimitsCache limitsCache;
	
	@Resource
	private UserLimitsMapper userLimitsMapper;
	
	@Resource
	private UserMapper userMapper;
	/* 
	 * 条件查询所有角色信息
	 * @see com.prince.service.back.service.RoleService#findRole(java.util.Map, com.prince.page.Page)
	 */
	@Override
	public Map<String, Object> findRole(Map<String, Object> params, Page page) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();

		if (null == params || params.size() == 0) {
			logger.debug("[RoleServiceImpl] findRole param beanJson is null");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}

		if (null == page) {
			logger.debug("[RoleServiceImpl] findRole page  is null");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//获取session 中的对象 
		if(null == params.get("user")) {
			logger.debug("登录用户为空");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		
		
		RoleExample roleExample = new RoleExample();
		Criteria createCriteria = roleExample.createCriteria();
		
		//通过session中的用户id查询
		User user = (User) params.get("user");
		if(!StringUtil.stringEquals(Constants.ADMIN,user.getBelongType())) {
			if(null !=user.getParentId() && Constants.ZERO != user.getParentId()) {
				//员工查上级手机号   管理员查自己手机号
				if(StringUtil.stringEquals(Constants.STAFF, user.getBelongType())){
					createCriteria.andUserIdEqualTo(user.getParentId());
				}else {
					createCriteria.andUserIdEqualTo(user.getId());
				}
			}
		}
		
		// 条件：角色名称和状态
		if (MapUtil.isNotEmpty(params, "name")) {
			createCriteria.andNameLike("%"+params.get("name").toString()+"%");
		}
		if (MapUtil.isNotEmpty(params, "status")) {
			createCriteria.andStatusEqualTo(params.get("status").toString());
		}

		int total = roleMapper.countByExample(roleExample);

		roleExample.setPage(page);
		roleExample.setOrderByClause("created desc");
		List<Role> list = roleMapper.selectByExample(roleExample);
		if (list == null) {
			logger.debug("[RoleServiceImpl] findRole 没有找到角色信息");
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}

		// 根据 roleId 查询 limits
		for (int i = 0; i < list.size(); i++) {
			StringBuilder sb = selectLimitsByRoleid(list.get(i).getId());
			list.get(i).setDescribed(sb.toString());
		}
		return response.toHashMapByPage(total, list);
	}

	/**
	 * 通过roleid查询权限菜单
	 * 
	 * @param id
	 * @return
	 */
	private StringBuilder selectLimitsByRoleid(int id) {
		logger.info("[RoleServiceImpl] selectLimitsByRoleid  通过roleid查询权限菜单");
		List<Limits> selectByLimitsId = roleLimitsMapper.selectByRoleId(id);
		StringBuilder sb = new StringBuilder();
		for (int j = 0; j < selectByLimitsId.size(); j++) {
			sb.append(selectByLimitsId.get(j).getName());
			if (j != selectByLimitsId.size() - 1) {
				sb.append(",");
			}
		}
		return sb;
	}
	
	

	/* 
	 * 添加角色信息
	 * @see com.prince.service.back.service.RoleService#addRole(com.prince.model.Role)
	 */
	@Override
	public Map<String, Object> addRole(Role role,User user) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		logger.info("[RoleServiceImpl] addRole  添加角色");
		//判断重名
		RoleExample roleExample = new RoleExample();
		Criteria createCriteria = roleExample.createCriteria();
		if(!StringUtil.isEmpty(role.getName())) {
			createCriteria.andNameEqualTo(role.getName());
		}
		List<Role> list = roleMapper.selectByExample(roleExample);
		if(!list.isEmpty()) {
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.duplicateName).toHashMap();
		}
		
		// 补全需要添加的数据
		role.setCreated(new Date());
		if(null !=user.getParentId() && !StringUtil.stringEquals(Constants.ADMIN,user.getBelongType())) {
			//员工查上级手机号   管理员查自己手机号
			if(StringUtil.stringEquals(Constants.STAFF, user.getBelongType())){
				role.setUserId(user.getParentId());
			}else {
				role.setUserId(user.getId());
			}
		}
		
		// 父id   session中belongType  员工添加父id  不是员工添加自己的id
		Integer id = user.getId();
		if(StringUtil.stringEquals(Constants.STAFF, user.getBelongType())) {
			id=user.getParentId();
		}
		role.setUserId(id);
		
		// 将描述里的数据拿出来单独添加到中间表里
		String str = role.getDescribed();
		role.setDescribed("");
		int insertSelective = roleMapper.insertSelective(role);
		
		if (!(insertSelective > 0)) {
			logger.debug("[RoleServiceImpl] addRole 插入失败", JSON.toJSONString(role));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		//将新增权限添加到redis中
		
		// for循环数据添加打list中
		if(StringUtil.isEmpty(str)) {
			return response.toHashMap();
		}
		String[] split = str.split(",");
		
		
		ArrayList<Map<String,Integer>> listMap = new ArrayList<>();
		for (String s : split) {
			Map<String,Integer> map =new HashMap<>();
			map.put("roleid", role.getId());
			map.put("limitsid",Integer.parseInt(s));
			// 批量插入role_limits 中间表
			listMap.add(map);
		}
		roleLimitsMapper.insertRoleLimits(listMap);
		return response.toHashMap();
	}

	/* 
	 * 根据id查询角色
	 * @see com.prince.service.back.service.RoleService#findRoleById(java.lang.Integer)
	 */
	@Override
	public Map<String, Object> findRoleById(Integer id) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();

		Role role = roleMapper.selectByPrimaryKey(id);
		if (role == null) {
			logger.debug("[RoleServiceImpl] findRoleById 没有这个角色", JSON.toJSONString(id));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}

		StringBuilder limit = selectLimitsByRoleid(id);
		role.setDescribed(limit.toString());

		response.put("data", role);
		return response.toHashMap();
	}
	
	/* 
 	 * 根据角色id查看limitsId
	 * @see com.prince.service.back.service.RoleService#findRoleLimitsId(java.lang.Integer)
	 */
	@Override
	public Map<String, Object> findRoleLimitsId(Integer id) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();

		Role role = roleMapper.selectByPrimaryKey(id);
		if (role == null) {
			logger.debug("[RoleServiceImpl] findRoleLimitsId 没有这个角色", JSON.toJSONString(id));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}

		List<Limits> selectByLimitsId = roleLimitsMapper.selectByRoleId(id);
		StringBuilder sb = new StringBuilder();
		for (int j = 0; j < selectByLimitsId.size(); j++) {
			sb.append(selectByLimitsId.get(j).getId());
			if (j != selectByLimitsId.size() - 1) {
				sb.append(",");
			}
		}
		role.setDescribed(sb.toString());

		response.put("data", role);
		return response.toHashMap();
	}


	/* 
	 * 修改角色
	 * @see com.prince.service.back.service.RoleService#updateRole(com.prince.model.Role)
	 */
	@Override
	@Transactional
	public Map<String, Object> updateRole(Role role) {
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		logger.info("[RoleServiceImpl] updateRole 更新角色");
		
		//判断重名
		if(StringUtil.isNotEmpty(role.getName()) ){
			RoleExample roleExample = new RoleExample();
			Criteria createCriteria = roleExample.createCriteria();
			createCriteria.andNameEqualTo(role.getName());
			List<Role> list = roleMapper.selectByExample(roleExample);
			if(ListUtils.isNotEmpty(list)) {
				if(role.getId() != list.get(0).getId())
					return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.duplicateName).toHashMap();
			}
		}
		
		String str = role.getDescribed();
		role.setDescribed("");
		int i = roleMapper.updateByPrimaryKeySelective(role);
		if (!(i > 0)) {
			logger.debug("[RoleServiceImpl] updateRole 更新失败!", JSON.toJSONString(role));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		if(StringUtil.isEmpty(str)) {
			//str为空 是没有权限 //删除中间表的roleId
			 roleLimitsMapper.deleteByRoleid(role.getId());
		}else {
			//中间表 先删除在添加
			roleLimitsMapper.deleteByRoleid(role.getId());
			
			// for循环数据添加打list中
			String[] split = str.split(",");
			ArrayList<Map<String,Integer>> listMap = new ArrayList<>();
			for (String s : split) {
				Map<String,Integer> map =new HashMap<>();
				map.put("roleid", role.getId());
				map.put("limitsid",Integer.parseInt(s));
				// 批量插入role_limits 中间表
				listMap.add(map);
			}
			roleLimitsMapper.insertRoleLimits(listMap);
		}
		
		//更新redis 缓存
//		limitsCache.del(role.getId().toString());		
//		List<String> limitList = userLimitsMapper.selectRoleIdByAddr(role.getId());
//		limitsCache.set(role.getId().toString(), limitList.toString());
		
		return response.toHashMap();
	}

	/* 
	 *  父id查询角色
	 * @see com.prince.service.back.service.RoleService#findRoleAll()
	 */
	@Override
	public Map<String, Object> findRoleAll() {
		logger.info("[RoleServiceImpl] findRoleAll 查询角色");
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		RoleExample example = new RoleExample();
				List<Role> list = roleMapper.selectByExample(example);
		response.put("data", list);
		return response.toHashMap();
	}

	/* 
	 * 删除角色  
	 * @see com.prince.service.back.service.RoleService#delRole(com.prince.model.Role)
	 */
	@Override
	public Map<String, Object> delRole(Role role) {
		logger.info("[RoleServiceImpl] delRole 删除角色");
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		int j = roleLimitsMapper.deleteByRoleid(role.getId());
		if(!(j>0)){
			logger.debug("[RoleServiceImpl] delRole 删除权限中间表失败！");
		}
		int i = roleMapper.deleteByPrimaryKey(role.getId());
		if (!(i > 0)) {
			logger.debug("[RoleServiceImpl] delRole 更新失败!", JSON.toJSONString(role));
			return CommonWebResponse.getCommonRespCodeMsgParams(WebCode.systemError).toHashMap();
		}
		return response.toHashMap();
	}

	/* 
	 * 根据条件查询
	 * @see com.prince.service.back.service.RoleService#findRoleByIdentifying(java.lang.String)
	 */
	@Override
	public Role findRoleByIdentifying(String identifying) {
		RoleExample roleExample = new RoleExample();
		Criteria criteria = roleExample.createCriteria();
		if(StringUtil.isNotEmpty(identifying)){
			criteria.andIdentifyingEqualTo(identifying);
		}
		List<Role> roleList = roleMapper.selectByExample(roleExample);
		return null == roleList || roleList.size() == 0 ?null:roleList.get(0);
	}

	/*
	 * 查询角色
	 * @see com.prince.service.back.service.RoleService#findUserRole()
	 */
	@Override
	public Map<String, Object> findUserRole(User user) {
		logger.info("[RoleServiceImpl] findRoleAll 查询角色");
		ResultParams response = CommonWebResponse.getSuccessResponseCodeMsgParams();
		RoleExample example = new RoleExample();
		//通过session中的用户id查询
		// 补全需要添加的数据
		if(!StringUtil.stringEquals(Constants.ADMIN,user.getBelongType())) {
			if(null !=user.getParentId() && Constants.ZERO != user.getParentId()) {
				//员工查上级手机号   管理员查自己手机号
				if(StringUtil.stringEquals(Constants.STAFF, user.getBelongType())){
					example.createCriteria().andUserIdEqualTo(user.getParentId());
				}else {
					example.createCriteria().andUserIdEqualTo(user.getId());
				}
			}
		}
		// 补全需要添加的数据
		List<Role> list = roleMapper.selectByExample(example);
		response.put("data", list);
		return response.toHashMap();
	}

}
